<template>
  <s-layout :title="product.name || '产品详情'">
    <view class="detail-container">
      <scroll-view scroll-y class="content-scroll">
        <!-- 商品主图 -->
        <image class="product-main-image" :src="product.image" mode="widthFix" />

        <!-- 商品信息 -->
        <view class="product-info-card">
          <view class="product-name">{{ product.name }}</view>
          <view class="product-desc">{{ product.description }}</view>
          <view class="product-price">¥{{ currentPrice }}</view>
        </view>

        <!-- 规格选择 -->
        <view class="spec-card" v-if="product.specs && product.specs.length > 0">
          <view class="spec-group" v-for="spec in product.specs" :key="spec.id || spec.name">
            <view class="spec-group-header">
              <view class="spec-group-name">
                {{ spec.name }}
                <text class="spec-count">({{ spec.options.length }} 个可选)</text>
              </view>
            </view>
            <view class="spec-options">
              <button
                class="spec-option"
                v-for="option in spec.options"
                :key="option.id || option.name"
                :class="{ active: isOptionSelected(spec, option) }"
                @click="selectSpec(spec, option)"
              >
                <view class="option-name">{{ option.name }}</view>
                <view class="option-price" v-if="option.price && option.price > 0">
                  +¥{{ option.price }}
                </view>
              </button>
            </view>
          </view>
        </view>
      </scroll-view>

      <!-- 底部操作栏 -->
      <view class="bottom-bar">
        <view class="price-section">
          <text>¥</text>
          <text class="price-value">{{ currentPrice }}</text>
        </view>
        <button class="add-to-cart-btn" @click="addToCart">加入购物车</button>
      </view>
    </view>
  </s-layout>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import sheep from '@/sheep';
import { onLoad } from '@dcloudio/uni-app';
import { 
  getSpecKey, 
  getOptionKey, 
  findOption, 
  safeParseFloat, 
  buildSpecsText, 
  parsePrice,
  parseOriginalPrice,
  buildFullSelectedSpecs,
  stripHtmlTags
} from './common/product-utils.js';

const cateringStore = sheep.$store('catering');

const product = reactive({
  id: 0,
  name: '',
  image: '',
  description: '',
  basePrice: 0,
  originalPrice: 0,  // 原价（第三方价格）
  specs: []
});

const selectedSpecs = reactive({});

onLoad(async (options) => {
  const passedProductId = options.productId || options.id;
  const passedShopId = options.shopId;

  if (!passedProductId) {
    uni.showToast({ title: '缺少商品信息', icon: 'error' });
    setTimeout(() => sheep.$router.back(), 1500);
    return;
  }
  
  const store = cateringStore.storeInfo;
  const shopId = passedShopId || (store && (store.shopId || store.id));
  if (!shopId) {
    uni.showToast({ title: '请先选择门店', icon: 'error' });
    setTimeout(() => sheep.$router.back(), 1500);
    return;
  }

  console.log('【KFC】加载商品详情:', { productId: passedProductId, shopId });
  
  uni.showLoading({ title: '加载中...' });
  try {
    const res = await sheep.$api.catering.getProductDetail(passedProductId, shopId);
    uni.hideLoading();
    
    if ((res.code === 0 || res.code === 200) && res.data) {
      parseProductData(res.data, options);
    } else {
      uni.showToast({ title: '加载商品失败', icon: 'none' });
      setTimeout(() => sheep.$router.back(), 1500);
    }
  } catch (error) {
    uni.hideLoading();
    console.error('【KFC】加载商品详情失败:', error);
    uni.showToast({ title: '加载商品失败', icon: 'error' });
    setTimeout(() => sheep.$router.back(), 1500);
  }
});

// 解析 KFC 商品数据
function parseProductData(apiData, options) {
  // 基础信息
  product.id = apiData.product_id || apiData.productId || options.productId;
  product.name = apiData.product_name || apiData.productName || options.name || '';
  product.image = apiData.product_img || apiData.productImg || '';
  // ✅ 处理HTML格式的描述
  const rawDesc = apiData.product_description || apiData.productDescription || '';
  product.description = stripHtmlTags(rawDesc);
  product.basePrice = parsePrice(apiData);           // 售价（系统设置）
  product.originalPrice = parseOriginalPrice(apiData); // 原价（第三方价格）

  console.log('【KFC】基础价格:', product.basePrice, '原价:', product.originalPrice);

  const details = apiData.details || apiData;
  
  // ✅ 解析肯德基 spec_sets 格式（优先）
  if (details.spec_sets && Array.isArray(details.spec_sets)) {
    console.log('【KFC】解析 spec_sets 规格:', JSON.stringify(details.spec_sets, null, 2));
    
    // spec_sets[] -> specs[].id (linkId) -> options[].id (productId) -> price
    const parsedSpecs = [];
    details.spec_sets.forEach(specSet => {
      if (specSet.specs && Array.isArray(specSet.specs)) {
        specSet.specs.forEach(spec => {
          parsedSpecs.push({
            id: spec.id || spec.spec_id,  // linkId
            name: spec.name || spec.spec_name || '',
            options: (spec.options || []).map(opt => ({
              id: opt.id || opt.option_id,  // productId
              name: opt.name || opt.option_name || '',
              price: safeParseFloat(opt.price || opt.add_price || 0)
            }))
          });
        });
      }
    });
    
    if (parsedSpecs.length > 0) {
      product.specs = parsedSpecs;
      console.log('【KFC】解析到 spec_sets 规格:', parsedSpecs.length, '个');
    }
  }
  
  // ✅ 解析通用规格结构（后备方案）
  if ((!product.specs || product.specs.length === 0) && (details.specs || details.specGroups)) {
    console.log('【KFC】解析 specs/specGroups 规格');
    product.specs = (details.specs || details.specGroups || []).map(spec => ({
      id: spec.id || spec.specId,
      name: spec.name || spec.specName,
      options: (spec.options || spec.items || []).map(opt => ({
        id: opt.id || opt.optionId,
        name: opt.name || opt.optionName,
        price: safeParseFloat(opt.price || opt.addPrice)
      }))
    }));
  }

  console.log('【KFC】最终规格数量:', product.specs?.length || 0);
  
  // 初始化默认选中
  initializeDefaultSelection();
}

// 初始化默认选中
function initializeDefaultSelection() {
  product.specs.forEach(spec => {
    if (!spec.options || spec.options.length === 0) return;
    
    const defaultOption = spec.options[0];
    selectedSpecs[getSpecKey(spec)] = getOptionKey(defaultOption);
  });
}

// 判断选项是否被选中
function isOptionSelected(spec, option) {
  return selectedSpecs[getSpecKey(spec)] === getOptionKey(option);
}

// 选择规格
function selectSpec(spec, option) {
  const specKey = getSpecKey(spec);
  const optionKey = getOptionKey(option);
  
  selectedSpecs[specKey] = optionKey;
  console.log('【KFC】当前已选规格:', JSON.parse(JSON.stringify(selectedSpecs)));
}

// 计算当前价格
const currentPrice = computed(() => {
  let finalPrice = product.basePrice;
  
  // 规格加价
  product.specs.forEach(spec => {
    const specKey = getSpecKey(spec);
    const selectedOptionKey = selectedSpecs[specKey];
    if (!selectedOptionKey) return;
    
    const option = findOption(spec, selectedOptionKey);
    if (option?.price) {
      finalPrice += option.price;
    }
  });
  
  return finalPrice.toFixed(2);
});

// 加入购物车
function addToCart() {
  // 构建完整的规格对象（包含 id 和 linkId）
  const fullSelectedSpecs = buildFullSelectedSpecs(product.specs, selectedSpecs);
  
  const cartItem = {
    id: product.id,
    name: product.name,
    image: product.image,
    price: parseFloat(currentPrice.value),        // 售价（系统设置）
    originalPrice: product.originalPrice,         // 原价（第三方价格）
    selectedSpecs: fullSelectedSpecs,
    specsText: buildSpecsText(product.specs, selectedSpecs),
    brandOt: 1,  // ✅ 肯德基品牌类型
  };

  console.log('【KFC】加入购物车 - 售价:', cartItem.price, '原价:', cartItem.originalPrice);
  console.log('【KFC】规格数据:', JSON.stringify(fullSelectedSpecs, null, 2));
  cateringStore.addToCart(cartItem);

  uni.showToast({ title: '已加入购物车', icon: 'success' });
  setTimeout(() => sheep.$router.back(), 1000);
}
</script>

<style lang="scss" scoped>
@import './common/product-detail.scss';

// KFC特有样式
.spec-group-name {
  .spec-count {
    color: #999;
    font-size: 24rpx;
    margin-left: 10rpx;
  }
}
</style>

